package com.smartplatform.websocket;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author 咕唧
 * @Date 2022/5/31 21:42
 * @Version 1.0
 * 当前对象是单例对象
 */

public class MyTextMessageHandler extends TextWebSocketHandler {

    private static Map<String, WebSocketSession> allClient = new ConcurrentHashMap<>();

    /**
     * 当客服端建立连接之后执行
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //请求的什么地址建立的连接
        String uri = session.getUri().toString();
        String name = uri.substring(uri.lastIndexOf("/") + 1);
        session.getAttributes().put("name", name);
        allClient.put(name, session);
        System.out.println("MyTextMessageHandler的afterConnectionEstablished方法执行了");
        super.afterConnectionEstablished(session);
    }

    /**
     * 服务器接收消息后执行
     *
     * @param session 发送消息的会话对象
     * @param message 发送的消息
     * @throws Exception
     */

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.err.println("MyTextMessageHandler的handleTextMessage方法执行了===="+message);
        super.handleTextMessage(session, message);
    }

    /**
     * 处理心跳方法
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        super.handleMessage(session, message);
    }

    /**
     * 当客户端关闭连接时执行
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.err.println("MyTextMessageHandler的afterConnectionClosed方法执行了");
        //移除会话
        allClient.remove(session.getAttributes().get("name"));
        super.afterConnectionClosed(session, status);
    }
}
